// freeCourseRecord.js
var recordTimer;//记录学习时间计时器
var freeCourseStart;//标准课开始时间
function prepareFreeCourseRecordNotifi(){
	api.addEventListener({
	    name: 'freeStartRecordNotifi'
	}, function(ret, err) {
	    updateFreeCourseRecord(ret.value);
	});
	api.addEventListener({
		name: 'freeCourseStart'
	},function(ret,err){
		freeCourseStart=Date.parse(new Date());
		console.log("开始时间:"+freeCourseStart);
	});
	//结束时调用
	api.addEventListener({
	    name: 'freeCourseRecordNotifi'
	}, function(ret, err) {
		console.log(Date.parse(new Date())-freeCourseStart);
		if(Date.parse(new Date())-freeCourseStart<60*1000){
			//学习时长不够一分钟
			return;
		}
		var cfnetChapterLogDetId = $api.getStorage('cfnetChapterLogDetId');
		//如果记录学习id不存在则不执行操作
		if (cfnetChapterLogDetId == '') {
			return;
		}
		var param = ret.value;
		param["log_det_id"] = cfnetChapterLogDetId;
		param["status"] = '1';
	    recordFreeChapterStatus(param);
	});
	//每分钟调用一次记录学习时间的id
	api.addEventListener({
	    name: 'endFreeChapterStudyTimeNotifi'
	}, function(ret, err) {
	    stopRecordTimer();
	    var cfnetChapterLogDetId = $api.getStorage('cfnetChapterLogDetId');
	    var param = ret.value;
		//如果记录学习id不存在则不执行操作
		if (cfnetChapterLogDetId == '' || param.vid == null) {
			return;
		}
	    param["log_det_id"] = cfnetChapterLogDetId;
	    endUpdateFreeCourseRecord(param);//退出时记录一次
	});
}
//记录自由课程学习状态
function recordFreeChapterStatus(param){
	// console.log(url_EndRecordFreeChapterStudyTime+'\n'+JSON.stringify(param));
	cfnetppPOST(url_EndRecordFreeChapterStudyTime, param, false, function(data, status){
		if (status == 'success') {
    		if (data.code == 200) {
				//清空学习id
    			$api.setStorage('cfnetChapterLogDetId', '');
    		}
    	}
	});
}
function startRecordTimer(param){
	//每分钟调用一次
	recordTimer = setInterval(function(){
		endUpdateFreeCourseRecord(param);
	}, 60000);
}
function stopRecordTimer(){
	// console.log('停止计时器');
	//停止计时器
	clearInterval(recordTimer);
}
function updateFreeCourseRecord(param){
    cfnetppPOST(url_freeChapterStartRecord, param, false, function(data, status){
    	// console.log('updateFreeCourseRecord:'+JSON.stringify(data));
    	if (status == 'success') {
    		if (data.code == 200) {
    			//存储当前正在记录的id
    			$api.setStorage('cfnetChapterLogDetId', data.data.log_det_id);
				param["log_det_id"] = data.data.log_det_id;
				startRecordTimer(param);
    		}
    	}
    });
}
function endUpdateFreeCourseRecord(param){
	// console.log(url_freeChapterEndRecord+JSON.stringify(param));
	cfnetppPOST(url_freeChapterEndRecord, param, false, function(data, status){
		// console.log('endUpdateFreeCourseRecord:'+JSON.stringify(data));
	});
}